package com.sam.stockvalue.config;

import com.sam.stockvalue.controller.ProcessSVController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author:
 */
@Component
public class QuartzConfig {

    @Autowired
    ApplicationContext applicationContext;

    @Value("${mail.send.cron}")
    String cronExpress;

    /**
     * 创建job对象
     * @return
     */
    @Bean
    public JobDetailFactoryBean jobDetailFactoryBean() {
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        jobDetailFactoryBean.setJobClass(ProcessSVController.class);
        return jobDetailFactoryBean;
    }

    /**
     * 创建trigger对象 - cron表达式对象
     * @param jobDetailFactoryBean
     * @return
     */
    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setCronExpression(cronExpress);
        // 关联JobDetail对象
        cronTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        return cronTriggerFactoryBean;
    }

    /**
     * 创建trigger对象 - 一般对象
     * @param jobDetailFactoryBean
     * @return
     */
    @Bean
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean) {
        SimpleTriggerFactoryBean simpleTriggerFactoryBean = new SimpleTriggerFactoryBean();
        // 关联JobDetail对象
        simpleTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        // 设置重复次数,这里配置的是重复次数，而不是总次数； 总次数=重复次数+1，也就是说这里配置的次数是：执行完一次之后，再重复执行的次数
        simpleTriggerFactoryBean.setRepeatCount(0);
        // 设置间隔时间
        simpleTriggerFactoryBean.setRepeatInterval(2000);
        return simpleTriggerFactoryBean;
    }

    /**
     * 创建schedule对象
     * @param triggerFactoryBean
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean triggerFactoryBean){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        //解决quartz中不能获取spring bean的问题
        schedulerFactoryBean.setApplicationContext(applicationContext);
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext");
        schedulerFactoryBean.setTriggers(triggerFactoryBean.getObject());
        return schedulerFactoryBean;
    }
}
